package com.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chat.entity.Chat;
import com.chat.entity.Info;
import com.chat.entity.Record;
import com.chat.entity.Users;
import com.chat.service.ChatService;
import com.chat.service.UsersService;
import com.chat.util.Util;
import com.chat.vo.TokenVo;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository
public class ChatImpl implements ChatService {



    @Autowired
    private MongoTemplate DB;
    @Autowired
    private UsersService UserDB;
    @Override
    public Long getId(String token){

        TokenVo tokenVo= Util.verifyToken(token);
        if(tokenVo.isSucceed==true){

            Map<String,Object> tokenMap=(Map<String,Object>)tokenVo.data;
            Map<String,Object> map=new HashMap<String,Object>();
            System.out.println(tokenMap);
            System.out.println(map);
            map.put("username",tokenMap.get("username").toString().replace("\"",""));
            System.out.println(map);
            List resArr=UserDB.selectByMap(map);
            System.out.println(resArr);
            if(resArr.size()!=0){
                Users users=(Users)resArr.get(0);
                return users.getId();
            }else{
                return -1l;
            }
        }else{
            return -1l;
        }
    }
    @Override
    public List getMessages(String token){
        Long id=this.getId(token);
        System.out.println("id"+id);
        if(id==-1){
            return new ArrayList<>();
        }else{
            Query query=new Query(Criteria.where("id").is(id));
            List<Chat> chats=DB.find(query,Chat.class);
            return chats;
        }
    }
    @Override
    public Boolean addMessage(Long id,Long uid,String message,Boolean isMe){
            Query query = new Query(Criteria.where("id").is(id));
            UpdateDefinition update =null;
            //1先判断数据库有无records 如果无再判断有无chat
            //完成 直接获取这个chat然后用代码判断
            List<Chat> chats=DB.find(query,Chat.class);
            if(chats.size()==0) {
                if(this.initUserRecord(id)==true){
                    return this.addMessage(id,uid,message,isMe);
                }else{
                    return false;
                }
            }else{//现在开始数据库中有这个id的聊天，不过不一定有和uid的聊天
                List<Record> records=chats.get(0).getRecords();
                Record record = new Record();
                record.setUid(uid);

                Info info = new Info();
                info.setTime(new Date().getTime());
                info.setState(1);
                info.setMessage(message);
                info.setIsMe(isMe);
                List<Info> infos=new LinkedList<Info>();
                infos.add(info);
                Boolean isRecords=false;
                for(Record temp:records){
                    if(temp.getUid().equals(uid)){
                        isRecords=true;
                        break;
                    }
                }
                if(isRecords!=true){//如果没有和uid的聊天记录一种写入方式
                    record.setInfo(infos);
                    update =new Update().push("records",record);
                }else{//已有记录直接添加info
                    query = new Query(Criteria.where("id").is(id)
                            .and("records").elemMatch(Criteria.where("uid").is(uid)));
                    update =new Update().push("records.$.info",info);
                }
            }
//            Thread.currentThread().sleep(10);//毫秒
            UpdateResult result=DB.updateMulti(query,update,Chat.class);
            if(result.getModifiedCount()==0){//这里可以去查查数据库是否有数据
                return false;
            }else{
                return true;
            }
    }
    @Override
    public Boolean sendMessage(Long id, Long uid, String message){
        return this.addMessage(id,uid,message,true)&&
               this.addMessage(uid,id,message,false);
    }
    @Override
    public Boolean initUserRecord(Long id){
        System.out.println(id);
        Boolean returnValue=false;
        //先判断是否已存在
        Query query = new Query(Criteria.where("id").is(id));
        List<Chat> result=DB.find(query,Chat.class);
        System.out.println(result);
        if(result.size()!=0){
            System.out.println("失败");
        }else{
            try{
                Chat chat = new Chat();
//                chat.set_id("6322cec338fe4241b3f0f0da");
                chat.setId(id);
                List<Record> records=new LinkedList<Record>();
                System.out.println(records);
                chat.setRecords(records);
                DB.insert(chat);
                returnValue=true;
            }catch (Exception error){
                error.printStackTrace();

            }
        }
        return returnValue;
    }
    @Override
    public Boolean setMessageState(Long id, Record record,Integer state){
//        List<Chat> chats;
//        Query query = new Query(Criteria.where("id").is(id));
//        chats=DB.find(query,Chat.class);
//        if(chats.size()==0){
//            System.out.println("找不到用户聊天记录");
//            return false;
//        }
//        List<Record> records=chats.get(0).getRecords();
//        Integer index=records.indexOf(record);
//        if(index==-1){
//            System.out.println("找不到消息");
//            return false;
//        }
//        record.setState(state);//设置状态
//        records.set(index,record);//修改聊天记录
//        UpdateDefinition updata =new Update().set("records",records);
//        if(DB.updateMulti(query,updata,Chat.class).getModifiedCount()==1){
//            return true;
//        }
        return false;

    }
    @Override
    public List findUsers(String token,String username){
        TokenVo tokenVo=Util.verifyToken(token);
        if(tokenVo.isSucceed==true&&username!=null&&username!=""){
            Map<String,Object> map=new HashMap<>();
            map.put("username",username);
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(true, "username", username);
            return UserDB.selectList(queryWrapper);
        }else{
            return null;
        }
    }
}
